package com.nowcoder.community.controller;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.RedisKeyUtil;
import com.nowcoder.community.util.XaCommunityUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

import static com.nowcoder.community.util.XaCommunityConstant.ENTITY_TYPE_POST;
import static com.nowcoder.community.util.XaCommunityConstant.TOPIC_LIKE;
@Controller
public class LikeController {
    @Resource
    private LikeService likeService;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private EventProducer eventProducer;
    @Resource
    private RedisTemplate redisTemplate;
    @PostMapping("/like")
    @ResponseBody
    //当前线程用户 给该实体帖子点赞---触发点赞的事件
    public String like(int entityType,int entityId,int entityUserId,int postId){
        //1.获取当前线程用户
        User user = hostHolder.getUser();
        
        //2.调用实现层来喜欢该实体帖子
        likeService.like(user.getId(), entityType, entityId,entityUserId);
        
        //3.获得帖子的被喜欢数，和被当前用户的点赞状态
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        //4.给上面两个变量装入结果集
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);
        
        //5.触发点赞事件
        if(likeStatus==1){
            Event event = new Event()
                .setEntityUserId(entityUserId)
                .setData("postId",postId)
                .setEntityId(entityId)
                .setEntityType(entityType)
                .setUserId(user.getId())
                .setTopic(TOPIC_LIKE);
            eventProducer.fireEvent(event) ;
        }
        if(entityType == ENTITY_TYPE_POST) {
            // 计算帖子分数
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);
        }
        
        //.返回带有状态码和结果集的result
        return XaCommunityUtil.getJSONString(0,null,map);
    }
}